<template>
  <div>
    <div class="uploadFile">
      <el-form label-width="120px" :model="dataForm" class="dialog-form" label-position="right">
        <el-form-item label="上传文件">
          <!-- accept=".xls, .csv, .xlsx, .wps" -->
          <el-upload ref="upload" drag name="file" :auto-upload="false" :limit="1" :http-request="httpRequest"
            :action="apiUrl" :before-upload="beforeUpload" :on-success="uploadSuccess" :file-list="dataForm.file"
            :on-error="uploadError">
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div slot="tip" class="el-upload__tip">
              只能上传excel/wps格式的文件，且不超过200M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-table ref="tableFile" :data="filelist" :element-loading-text="elementLoadingText" height="30vh">
        <el-table-column show-overflow-tooltip prop="upload_time" label="上传日期" />
        <el-table-column show-overflow-tooltip prop="wenjianmc" label="文件名称" />
        <!-- <el-table-column show-overflow-tooltip prop="wenjianmc" label="预览">
          <template slot-scope="scope">
            <img :src="changeF(scope.row.wenjianlj)" alt="">
          </template>
</el-table-column> -->
        <el-table-column label="操作" fixed="right" min-width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="download(scope)">下载</el-button>
            <el-button type="text" @click="delfile(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doUpload">确定</el-button>
    </div>
  </div>
</template>

<script>
import {
  insertRukudbdFile,
  deleteFileByPara,
  downloadFileByPath,
  queryFileListByPara
} from '@/api/warehousing'
import axios from 'axios'
export default {
  props: {
    apiUrl: {
      type: String,
      default: '',
    },
    rowid: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      headers: {
        token: localStorage.getItem('token') || '',
        'content-Type': 'multipart/form-data'
      },
      dataForm: {},
      elementLoadingText: '正在加载...',
      filelist: []
    }
  },
  async mounted() {
    await this.getfilelist()
  },
  methods: {
    beforeUpload(file) {
      // if (!this.$util.validFile(file, 'excel')) {
      //   this.$message({
      //     message: '上传文件格式不正确!',
      //     type: 'error',
      //   })
      //   return false
      // }
      if (file.size / 1024 / 1024 > 200) {
        this.$message({
          message: '上传文件大小不能超过200MB!',
          type: 'error',
        })
        return false
      }
      return true
    },
    async getfilelist() {
      this.filelist = []
      let { data } = await queryFileListByPara({ rukudbdid: this.rowid })
      this.filelist = data
    },
    //替换反斜线
    changeF(str) {
      let data = str.replace("\\\\\\", '/')
      return data
    },
    async download(scope) {
      let data = {
        id: scope.row.id,
      }
      let url = scope.row.wenjianmc;
      let index = url.lastIndexOf(".");
      let str = url.substring(index + 1, url.length);
      this.postDownload('/rukudbd/downloadFileByPath', data, '凭证文件', str)
    },
    // 文件流下载
    postDownload(url, data, fileName, str) {
      return axios({
        // 用axios发送post请求
        url: 'http://localhost:8081' + url, // 请求地址
        data, // 参数
        method: 'post',
        responseType: 'blob',
        headers: {
          'Content-Type': 'multipart/form-data',
          token: localStorage.getItem('token'),
        },
      })
        .then((res) => {
          // 处理返回的文件流
          // 获取http头部的文件名信息，若无需重命名文件，将下面这行删去
          // if (!fileName) fileName = window.decodeURI(res.headers['content-disposition'].split('=')[1])

          /* 兼容ie内核，360浏览器的兼容模式 */
          const blob = new Blob([res.data], { type: res.data.type })
          /* 兼容ie内核，360浏览器的兼容模式 */
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName)
          } else {
            /* 火狐谷歌的文件下载方式 */
            let url1 = window.URL.createObjectURL(blob)
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url1

            link.setAttribute('download', fileName + `.${str}`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
          }
          this.$message({
            message: '下载成功',
            type: 'success',
          })
          return Promise.resolve(res.data)
        })
        .catch((err) => {
          this.$message({
            message: err,
            type: 'error',
          })
          return Promise.resolve(err)
        })
    },
    async delfile(scope) {
      this.$baseConfirm('是否删除文件附件', null, async () => {
        let data = await deleteFileByPara({ id: scope.row.id })
        this.filelist.splice(scope.$index, 1);
        if (data.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }
      })

    },
    httpRequest(param) {
      this.dataForm.file = param.file
    },
    uploadSuccess(res) {
      if (res.code == 200) {
        this.$message({
          message: '导入成功',
          type: 'success',
        })
        this.$emit('success')
      } else {
        this.$message({
          message: res.message,
          type: 'error',
        })
      }
    },
    uploadError(e) {
      this.$message({
        message: '上传失败，请按照指定的模板格式进行上传',
        type: 'error',
      })
    },
    async doUpload() {
      this.$refs.upload.submit()
      this.dataForm.rukudbdid = this.rowid
      let data = await insertRukudbdFile(this.dataForm)
      if (data.code == 200) {
        this.$message({
          message: '导入成功',
          type: 'success',
        })
        this.$emit('success')
      } else {
        this.$message({
          message: res.message,
          type: 'error',
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.uploadFile {
  display: flex;
}

::v-deep {

  .el-table th.el-table__cell {
    background-color: transparent;
  }

  .el-table {
    border: none;
    background-color: transparent;
  }

}
</style>
